import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router' 
// import pinia from '../store/pinia'
import config from '../config'

const router = useRouter()
const NETWORK_ERROR = '网络请求异常,请稍后重试......'


const service = axios.create({
    // baseURL:'https://www.fastmock.site/mock/d45efeb4c6c2cdbb2384dd8562c05d91/shopad'
    // baseURL:'http://127.0.0.1:3007'
    baseURL: config.baseApi
})

//添加请求拦截器 传入两个函数
service.interceptors.request.use(
    function(config){
        if(config.headers.Authorization === undefined){
            config.headers.Authorization ='Bearer ' +  localStorage.getItem('token') || ''
        }
        return config
    },
    function(err){
        console.log('请求失败',err)
        return Promise.error(err)
    }
)

//添加响应拦截器
service.interceptors.response.use(
    function(response){
        // if(response.code !== 200){
        //    return ElMessage.error(response.data.message || NETWORK_ERROR)
        // }
        console.log('response',response);
        return response.data
    },
    function(error){
        console.log('error',error);
        ElMessage.error(NETWORK_ERROR)
        localStorage.clear()
        router.push('/login')
        return Promise.reject(error)
    }
)

//封装的核心函数
function request(options){
    options.method = options.method || 'get'
    if(options.method.toLowerCase() == 'get'){
        options.params = options.data
    }
    //对mock的处理
    // let isMock = config.isMock
    let isMock = config.mock
    if(typeof options.mock !== 'undefined'){
        isMock = options.mock
        // console.log('isMock',isMock);
    }
    //对线上环境做处理
    if(config.env == 'prod'){
        //不给你用到mock的机会
        service.defaults.baseURL = config.baseApi
    }else{
        service.defaults.baseURL = isMock ? config.mockApi : config.baseApi
    }
    // console.log('isMock2',isMock,options.mock);

    //axios本身的请求语法就是axios({ url:'',method:'',data:{} })
    //所以options这个参数是一个对象，包含请求的相关属性。
    return service(options)

}



// export default service
export default request